'use strict';
const inquirer = require('inquirer'); // 用户与命令行交互工具

const config = require('../templates');
const chalk = require('chalk'); // 格式化输出颜色
let copyUtil = require('../utils/copyFolder');
var pathUtil = require('../utils/path');
var path = require('path');
var writeUtil = require('../utils/writeFile');
var gitUtil = require('../utils/git');

module.exports = async () => {
    // 处理用户输入
    const currentUrl = process.cwd(); // 获取Node.js 进程的当前工作目录

    // 1. 项目名称
    const {projectName} = await inquirer.prompt([
      {
        name: 'projectName',
        type: 'input'
      }
    ])

    if (!projectName) {
      console.log(chalk.red('\n × Project name does not exit!'));
      process.exit()
    }

    const targetUrl = path.join(currentUrl, projectName)
    const packageJson = path.join(targetUrl, 'package.json')

    const list = Object.keys(config.tpl).map((key)=> {
      return {
        name: key,
        value: key
      }
    }
  )

    // 2. 选择模板
    const {tplName} = await inquirer.prompt([
      {
        name: 'tplName',
        type: 'list',
        message: `Please choose a template`,
        choices: list
      }
    ])

    if (!tplName) {
      tplName = 'h5-vite-template';
    } else if (!config.tpl[tplName]) {
      console.log(chalk.red('\n × Template does not exit!'));
      process.exit()
    }

    const tplUrl = config.tpl[tplName].url
    /** 
     * 如果当前是配置的git地址，直接使用git clone拉取
     */
    if(/^https.*\.git$/.test(tplUrl)){
      let gitStr = `git clone ${tplUrl} ${projectName}`
      try {
        console.log(chalk.yellow('\nLinking git repository...'));
        await gitUtil.gitClone(gitStr)
        await writeUtil.writeJson(
          packageJson, 
          {name: projectName}
        )
       
      } catch(err) {
        console.log(err)
        process.exit()
      } 
   }else{
    const srcUrl = pathUtil.resolve(config.tpl[tplName].url);
    try {
      // 创建文件夹
      await copyUtil.createFolder(targetUrl)
      // 拷贝文件
      await copyUtil.copyFolder(
        srcUrl, // 源文件
        [path.join(srcUrl, 'node_modules'), path.join(srcUrl, 'dist')], // 不被拷贝的文件
        targetUrl // 目的文件
      )

      // 更改package.json的项目名称为用户输入
      await writeUtil.writeJson(
        packageJson, 
        {name: projectName}
      )
    } catch(err) {
      console.log(err)
      process.exit()
    } 
   }
    
    // 构建完毕-退出程序
    console.log(chalk.green('\nSuccess loaded ' + tplName));
    process.exit()
};
